package com.demo.sso.util;

import com.demo.sso.common.constant.Const;
import com.demo.sso.common.constant.ShiroSessionRedisConstant;
import com.demo.sso.enity.LoginUser;
import org.apache.shiro.session.Session;

import java.io.Serializable;

/**
 * 操作redis的工具类
 *
 * @author fengjy
 * @date 2018-10-30 20:15
 */
public class ShiroSessionRedisUtil {

    public static Session getSession(Serializable sessionId){
        Session session = null;
        byte [] key = (ShiroSessionRedisConstant.SHIROSESSION_REDIS_PREFIX+sessionId.toString()).getBytes();
        byte[] bytes = RedisUtil.getObject(ShiroSessionRedisConstant.SHIROSESSION_REDIS_DB
                , key
                , ShiroSessionRedisConstant.SHIROSESSION_REDIS_EXTIRETIME);
        if(bytes != null && bytes.length > 0){
            session = ShiroSessionConvertUtil.byteToSession(bytes);
        }
        return session;
    }

    /**
     * 更新redis中的session同时更新token时间
     * @param session
     */
    public static void updateSession(Session session){
        byte [] key = (ShiroSessionRedisConstant.SHIROSESSION_REDIS_PREFIX+session.getId().toString()).getBytes();
        RedisUtil.updateObject(ShiroSessionRedisConstant.SHIROSESSION_REDIS_DB
                , key
                , ShiroSessionConvertUtil.sessionToByte(session)
                , ShiroSessionRedisConstant.SHIROSESSION_REDIS_EXTIRETIME);
        //也要更新token
        LoginUser user = (LoginUser)session.getAttribute(Const.SESSION_USER);
        if(null != user){
            RedisUtil.updateString(ShiroSessionRedisConstant.SHIROSESSION_REDIS_DB
                    ,ShiroSessionRedisConstant.SSOTOKEN_REDIS_PREFIX+user.getUserId()
                    , ShiroSessionRedisConstant.SHIROSESSION_REDIS_EXTIRETIME);
        }
    }

    public static void deleteSession(Session session){
        RedisUtil.delString(ShiroSessionRedisConstant.SHIROSESSION_REDIS_DB
                ,ShiroSessionRedisConstant.SHIROSESSION_REDIS_PREFIX+session.getId().toString());
        //也要删除token
        LoginUser user = (LoginUser)session.getAttribute(Const.SESSION_USER);
        if(null != user){
            RedisUtil.delString(ShiroSessionRedisConstant.SHIROSESSION_REDIS_DB
                    ,ShiroSessionRedisConstant.SSOTOKEN_REDIS_PREFIX+user.getUserId());
        }
    }
}

